<?php
/**
 * APP消息推送.
 * User: dxk
 * Date: 2021-01-04
 */
namespace App\Library\Service\AliCloud;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

/**
 * @method array Push(array $options = [])
 *
 * @method array ListSummaryApps(array $options = [])
 *
 * @method array QueryDevicesByAccount(array $options = [])
 *
 * @method array BindAlias(array $options = [])
 * @method array UnbindAlias(array $options = [])
 * @method array QueryAliases(array $options = [])
 * @method array QueryDevicesByAlias(array $options = [])
 *
 * @method array BindTag(array $options = [])
 * @method array UnbindTag(array $options = [])
 * @method array QueryTags(array $options = [])
 * @method array ListTags(array $options = [])
 * @method array RemoveTag(array $options = [])
 *
 * @package App\Library\Service\AppPush
 */
class AppPush
{
    private $app_key;

    public function __construct($app_key)
    {
        $this->app_key = $app_key;
    }

    /**
     * 获取推送客户端
     * @return \AlibabaCloud\Client\Request\RpcRequest
     * @throws ClientException
     */
    private function instance()
    {
        AlibabaCloud::accessKeyClient(config('sys.aliyun.accessKeyId'), config('sys.aliyun.accessSecret'))
            ->regionId('cn-beijing')//指定请求的地域，不指定则使用客户端地域、默认地域。
            ->asDefaultClient();
        return AlibabaCloud::rpc()
            ->product('Push')
            // ->scheme('https') // https | http
            ->version('2016-08-01')
            ->method('POST')
            ->host('cloudpush.aliyuncs.com');//指定域名则不会寻址，如认证方式为Bearer Token的服务则需要指定。
    }

    /**
     * 请求方法
     * @param $name
     * @param $arguments
     * @return array
     */
    public function __call($name, $arguments)
    {
        if (empty($this->app_key)) {
            return alert_info(1, '未配置消息推送app_key');
        }
        $option = $arguments[0];
        $option['AppKey'] = $this->app_key;
        try {
            $result = $this->instance()->action($name)->options(['query' => $option])->request();
            $res = $result->toArray();
            easy_log('alicloud/apppush', ['action' => $name, 'options' => $option, 'res' => $res]);
            if (is_string($res)) {
                return alert_info(1, $res);
            }
            return alert_info(0, 'ok', $res);
        } catch
        (ClientException $e) {
            return alert_info(1, $e->getErrorMessage());
        } catch (ServerException $e) {
            return alert_info(1, $e->getErrorMessage());
        }
    }
}
